#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

typedef struct
{
    char name[20];
    int start;
    int end;
    int time;
} Race_args;

void *th_func(void *args)
{
    Race_args *a = (Race_args *)args;
    int i = a->start;
    for (; i <= a->end; ++i)
    {
        printf("%s(%lx) run %d M\n", a->name, pthread_self(), i);
        usleep(a->time);
    }

    return (void *)(a->end - a->start);
}

int main()
{

    pthread_t rabbit, tortoise;
    Race_args r_args = {"Rabbit", 0, 100, (int)(drand48() * 100000)};
    Race_args t_args = {"Tortoise", 40, 100, (int)(drand48() * 10000000)};

    if (pthread_create(&rabbit, NULL, th_func, (void *)&r_args) != 0)
    {
        perror("pthread_create error!");
    }

    if (pthread_create(&tortoise, NULL, th_func, (void *)&t_args) != 0)
    {
        perror("pthread_create error!");
    }

    int result;
    pthread_join(rabbit, (void *)&result);
    printf("Rabbit run %d M\n",result);
    pthread_join(tortoise, (void *)&result);
     printf("Tortoise run %d M\n",result);

    printf("Main control pthread %lx exit!\n", pthread_self());

    return 0;
}